<?php
namespace app\index\controller;

use app\common\controller\Auth;
use think\Controller;
use think\Db;
use think\Request;
use app\util\geetest\GeetestLib;

class Common extends Auth
{
    function __construct()
    {
        parent:: __construct();
        cookie(['prefix' => '', 'expire' => 3600 * 24, 'path' => '/']);
        $this->database = config('database');
        $this->date = date("Y-m-d H:i:s");
        if (config('web_logo') != '' || config('web_logo') != NULL) {
            define('LOGO', config('web_logo'));
        } else {
            define('LOGO', '/static/img/logo.png');
        }
		if (config('sys_is_qqjump') == 1 && is_ios()) {
            $this->is_Qq_jump();
        }
		if (Request::instance()->header("X-PJAX")) {
            config('default_ajax_return', 'html');
            define('PJAX', true);
        } else {
            define('PJAX', false);
        }
    }
	
	protected function is_Qq_jump()
    {
		if (preg_match('/QQ\//', $_SERVER['HTTP_USER_AGENT'])){
			header('Content-type:text/html;charset=utf-8');
			return jump();
			exit(0);
		}
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
			header('Content-type:text/html;charset=utf-8');
			return jump();
			exit(0);
		}
    }
	
	
	protected function geetest_check($geetest_challenge, $geetest_validate, $geetest_seccode)
    {
        $GtSdk = new GeetestLib(config('CAPTCHA_ID'), config('PRIVATE_KEY'));
        $data = array(
            "user_id" => time(), # 网站用户id
            "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => real_ip() # 请在此处传输用户请求验证时所携带的IP
        );
        if (session('gtserver') == 1) {   //服务器正常
            if ($GtSdk->success_validate($geetest_challenge, $geetest_validate, $geetest_seccode, $data)) {
                return true;
            } else {
                return false;
            }
        } else {  //服务器宕机,走failback模式
            if ($GtSdk->fail_validate($geetest_challenge, $geetest_validate, $geetest_seccode)) {
                return true;
            } else {
                return false;
            }
        }
    }
	
    public function geetest_captcha()
    {
        $GtSdk = new GeetestLib(config('CAPTCHA_ID'), config('PRIVATE_KEY'));
        $data = array(
            "user_id" => time(),
            "client_type" => "web",
            "ip_address" => real_ip()
        );
        $status = $GtSdk->pre_process($data, 1);
        session('gtserver', $status);
        session('user_id', $data['user_id']);
        echo $GtSdk->get_response_str();
    }
}